﻿using ProtoBuf;
using System.IO;

namespace ShareHelper
{
    /// <summary>
    ///
    /// </summary>
    public class PbUtil
    {
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="instance"></param>
        /// <returns></returns>
        public static byte[] Obj2Bytes<T>(T instance)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                Serializer.Serialize<T>(memoryStream, instance);
                return memoryStream.ToArray();
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="buffer"></param>
        /// <param name="offset"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static T Bytes2Obj<T>(byte[] buffer, int offset = 0, int length = 0)
        {
            if (buffer?.Length > 0 && buffer.Length >= offset + length)
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    if (length == 0)
                        length = buffer.Length;
                    memoryStream.Write(buffer, offset, length);
                    memoryStream.Position = 0;
                    return Serializer.Deserialize<T>(memoryStream);
                }
            }
            return default;
        }
    }
}